unit UnitKP;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Buttons, ExtCtrls, Math;

const
  N = 8;
  PW = 30;
  PH = 30;
  DH = 10;

type
  TForm1 = class(TForm)
    BitBtn1: TBitBtn;
    procedure BitBtn1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  k, l, x, y, x0, y0: Integer;
  pan: array of TPanel;
  mass: array of Integer;

implementation

{$R *.dfm}

procedure TForm1.BitBtn1Click(Sender: TObject);
var
  i, j, ii, m, d: Integer;
begin
  ii:=N-1;
  Randomize;
  for i:=0 to N-1 do
  begin
    mass[i]:=Random(50);
  end;
  for i:=0 to N-1 do
  begin
    pan[i]:=TPanel.Create(Form1);
    pan[i].Width:=PW;
    pan[i].Height:=PH;
    pan[i].Parent:=Form1;
  end;
  k:=Floor(Log2(N));
  d:=PW div 4;
  l:= N - (Floor(Power (2, k)) - 1);
  m:=k-1;
  x0:= 50 + (l-1)*(PW+d);
  y0:= k*(PH+DH) + 200;
  x:=x0;
  y:=y0;
  for i:= 1 to k+1 do
  begin
    if i = 1 then
    begin
      for j:= 1 to l do
      begin
        pan[ii].Left:=x;
        pan[ii].Top:=y;
        x:= x - PW - d;
        Dec(ii);
      end;
      x0:=x0 + (Floor(Power(2, k)) - l)*(PW + d);
      y:=y0;
    end else begin
      x0:= x0 - (d div 2) - (PW div 2);
      x:=x0;
      d:=d + 2*PW - (PW-d);
      y:= y - PH - DH;
      for j:= 1 to Floor(Power(2, m)) do
      begin
        pan[ii].Left:=x;
        pan[ii].Top:=y;
        x:=x - PW - d;
        Dec(ii);
      end;
      Dec(m);
    end;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  i: Integer;
begin
  SetLength(mass, N);
  SetLength(pan, N);
end;

end.
